import cv2
import numpy as np
import os


def show_img(img, title="title"):
    cv2.imshow(title, img)
    # 关闭窗口
    cv2.waitKey()
    cv2.destroyAllWindows()


# dirpath = 'temp'
# imgs = [os.path.join(dirpath, img) for img in os.listdir(dirpath)]
# img_a = imgs[0]
img_a = 'temp/a1.jpg'
# img_a = 'temp/a4.jpg'


# 读取名称为 p9.png的图片
# org = cv2.imread(img_a,1)
img = cv2.imread(img_a, 1)
img = cv2.resize(img, (720, 480))
# show_img(img, 'img')

# blur = cv2.pyrMeanShiftFiltering(img, 25, 10)
blur = cv2.GaussianBlur(img, (5, 5), 5)
# blur = cv2.GaussianBlur(img, (3, 3), 0)
# blur = img
# show_img(blur, 'blur')

gray = cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY)
# show_img(gray, 'gray')


# 提取边缘
edges = cv2.Canny(gray, 30, 250, apertureSize=3)
show_img(edges, 'edges')
# cv2.findSquares


def findMaxContour(image):
    # 寻找边缘
    # _, contours = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)     # contours, hierarchy
    contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)     # contours, hierarchy

    # 计算面积
    max_area = 0.0
    max_contour = []
    for contour in contours:
        currentArea = cv2.contourArea(contour)
        if currentArea > max_area:
            max_area = currentArea
            max_contour = contour
    return max_contour, max_area


# max_contour, max_area = findMaxContour(edges)
# cv2.drawContours(img, max_contour, -1, (255, 0, 0), 3)
# show_img(img, title='drawContours')


# 寻找直线--霍夫变换
if 1:
    img_black = img.copy()
    # img_black = np.zeros(img.shape, np.uint8)
    # 提取直线
    COLOR = (255, 0, 0)
    USE_HOUGH_P = 1
    if USE_HOUGH_P:
        # lines = cv2.HoughLinesP(edges, 3, 1.0 * np.pi / 180, threshold=200, minLineLength=100, maxLineGap=5)
        # lines = cv2.HoughLinesP(edges, 3, 1.0 * np.pi / 180, threshold=300)
        lines = cv2.HoughLinesP(edges, 4, np.pi / 180, 200, minLineLength=100, maxLineGap=10)

        assert lines is not None, 'lines为空!'

        LINE_LEN = 2000
        for (x1, y1, x2, y2) in lines[:, 0]:
            print(x1, y1, ";", x2, y2)
            cv2.line(img_black, (x1, y1), (x2, y2), COLOR, 3)  # 画直线

            # ax1 = int(x1 + LINE_LEN)
            # ay1 = int(y1 + LINE_LEN)
            # ax2 = int(x2 - LINE_LEN)
            # ay2 = int(y2 - LINE_LEN)
            # # 把直线显示在图片上
            # cv2.line(img_black, (ax1, ay1), (ax2, ay2), COLOR, 3)
    else:
        LINE_LEN = 2000
        lines = cv2.HoughLines(edges, 4, np.pi / 180, 200)
        assert lines is not None, 'lines为空!'
        print('lines.shape:', lines.shape)
        for line in lines:
            for rho, theta in line:
                a = np.cos(theta)
                b = np.sin(theta)
                x0 = a * rho
                y0 = b * rho
                x1 = int(x0 + LINE_LEN * (-b))
                y1 = int(y0 + LINE_LEN * (a))
                x2 = int(x0 - LINE_LEN * (-b))
                y2 = int(y0 - LINE_LEN * (a))
                # 把直线显示在图片上
                cv2.line(img_black, (x1, y1), (x2, y2), COLOR, 2)
    print('--- lines.shape:', lines.shape)
    show_img(img_black)


# 寻找最大矩形
if 1:
    _img = img.copy()
    img_findContours = img_black.copy()
    img_findContours = cv2.cvtColor(img_findContours, cv2.COLOR_BGR2GRAY)
    img_findContours = cv2.bitwise_not(img_findContours)
    # img_findContours = cv2.Canny(img_findContours, 30, 250, apertureSize=3)
    show_img(img_findContours, 'img_findContours')

    cnts_ls = cv2.findContours(img_findContours, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    len(cnts_ls)

    img.shape
    cnts = cnts_ls[0] if len(cnts_ls) == 2 else cnts_ls[1]
    for c in cnts:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.015 * peri, True)
        if len(approx) == 4:
            x, y, w, h = cv2.boundingRect(approx)
            # (x, y), (w, h), theta = cv2.minAreaRect(approx)
            print(approx)
            cv2.rectangle(_img, (x, y), (x + w, y + h), (36, 255, 12), 2)

    show_img(_img)


# 圆角矩形
if 1:
    # img = cv2.imread("image.png", -1)
    img_rect = np.zeros(img.shape, np.uint8)

    img_black = cv2.cvtColor(img_black, cv2.COLOR_BGR2GRAY)

    img_black = cv2.bitwise_not(img_black)

    contours, hierarchy = cv2.findContours(img_black, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(img_rect, (x, y), (x + w, y + h), (255, 0, 0), 2)

    show_img(img_rect)